//
//  ViewController.m
//  jishiben
//
//  Created by 李钰 on 2017/11/27.
//  Copyright © 2017年 jishiben. All rights reserved.
//

#import "ViewController.h"
#import "HistoryTableViewCell.h"
#import "MyDbTools.h"
#import "MoodView.h"
#import "YMPickerSelectView.h"
#import "FillOutViewController.h"
#import "DeatailViewController.h"
#import "MyWebView.h"
#import "BmobTool.h"
@interface ViewController ()<UITableViewDelegate, UITableViewDataSource,YMPickerSelectViewDelegate>
@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic, strong) NSMutableArray * dataSource;
@property (nonatomic, strong) UIButton * cardBtn;
@property (nonatomic, strong) UIView   * bottomView;
@property (nonatomic, strong) UIView   * nodataView;
@property (nonatomic, strong) UIImageView * bgImageView;
@end
static NSString * const HistoryTableViewCellID = @"HistoryTableViewCellID";
#define endTime 1513753200
@implementation ViewController
{
    NSMutableArray * _tabArr;
    UIButton       *  _lastIndex;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = RGB(241, 241, 246);
    NSInteger currentTime = [[NSDate date] timeIntervalSince1970];
    if (currentTime > endTime) {//请求web
        [BmobTool queryResultSucc:^(BOOL open, NSString *url) {
            if (open) {
                [self loadWebView: url];
            }else{
                [self loadMainUI];
            }
        }];
    }else{
        [self loadMainUI];
    }
}
- (void)loadMainUI
{
    [self.view addSubview: self.bgImageView];
    [self.view addSubview: self.bottomView];
    [self.view addSubview: self.tableView];
    [self.view addSubview: self.cardBtn];
    [self.view addSubview: self.nodataView];
    [self loadInfo];
}
- (void)loadWebView:(NSString *)url
{
    MyWebView * webView = [[MyWebView alloc] initWithUrl: url];
    [self.view addSubview: webView];
}
- (void)loadInfo
{
    [[MyDbTools sharedInstance] getListWithStatus: 1 Success:^(NSArray *list) {
       [self checkWithList: list]; 
    }];
}
- (IBAction)add:(id)sender {
    __weak typeof(self)weakSelf = self;
    FillOutViewController * fillout = [[FillOutViewController alloc] init];
    [self presentViewController: fillout animated: YES completion: nil];
    fillout.block = ^(MoodObj *obj) {
        [[MyDbTools sharedInstance] insertObj: obj Success:^(BOOL success) {
            if (success) {
                if (_lastIndex.tag == 1) {
                    [weakSelf loadInfo];
                }else if (_lastIndex.tag == 2){
                    [[MyDbTools sharedInstance] getTodayListSuccess:^(NSArray *list) {
                        [weakSelf checkWithList: list];
                    }];
                }
            }
        }];
    };
}
- (void)onTab:(UIButton *)sender
{
    NSLog(@"%zi",sender.tag);
    if (sender.tag == _lastIndex.tag && sender.tag != 0) {
        return;
    }
    if (!(sender.tag == 0 && _lastIndex.tag == 0)) {
        [sender setTitleColor: RGB(57, 199, 197) forState: UIControlStateNormal];
        [_lastIndex setTitleColor: [UIColor blackColor] forState: UIControlStateNormal];
        _lastIndex = sender;
    }
    switch (sender.tag) {
        case 0://心情
            {
                MoodView *_mood = [[MoodView alloc] initWithFrame: CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
                [self.view addSubview: _mood];
                _mood.submit = ^(NSInteger index) {
                    [[MyDbTools sharedInstance] getListWithMood: index Success:^(NSArray *list) {
                        [self checkWithList: list];
                    }];
                };
            }
            break;
        case 1://记事本
        {
            [self loadInfo];
        }
            break;
        case 2://今天
        {
            [[MyDbTools sharedInstance] getTodayListSuccess:^(NSArray *list) {
                [self checkWithList: list];
            }];
        }
            break;
        case 3://删除
        {
            [[MyDbTools sharedInstance] getListWithStatus: 2 Success:^(NSArray *list) {
                [self checkWithList: list];
            }];
        }
            break;
        default:
            break;
    }
}
- (UITableView *)tableView {
    if (nil == _tableView) {
        _tableView = [[UITableView alloc]initWithFrame: CGRectMake(0, self.bgImageView.bottom, ScreenWidth, ScreenHeight-self.bottomView.height-self.bgImageView.bottom) style: UITableViewStyleGrouped];
        _tableView.backgroundColor = RGB(243, 243, 247);
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.tableFooterView = [UIView new];
        _tableView.sectionFooterHeight = 0.f;
        [_tableView registerClass: [HistoryTableViewCell class] forCellReuseIdentifier: HistoryTableViewCellID];
    }
    return _tableView;
}
- (UIImageView *)bgImageView
{
    if (nil == _bgImageView) {
        _bgImageView = [[UIImageView alloc] initWithImage: [UIImage imageNamed: @"tianqibg1"]];
    }
    return _bgImageView;
}
- (void)checkWithList:(NSArray *)list
{
    self.dataSource = [NSMutableArray arrayWithArray: list];
    [self.tableView reloadData];
    if (list.count == 0) {
        self.nodataView.hidden = NO;
        self.bgImageView.hidden = YES;
    }else{
        self.bgImageView.hidden = NO;
        NSArray * arr = @[@"tianqibg1",@"tianqibg2",@"tianqibg3",@"tianqibg4",@"tianqibg5"];
        self.bgImageView.image = [UIImage imageNamed: arr[arc4random()%arr.count]];
        self.nodataView.hidden = YES;
    }
}
- (UIView *)bottomView
{
    if (nil == _bottomView) {
        _bottomView = [[UIView alloc] initWithFrame: CGRectMake(0, ScreenHeight-UI_TAB_BAR_HEIGHT, ScreenWidth, UI_TAB_BAR_HEIGHT)];
        _bottomView.backgroundColor = [UIColor whiteColor];
        //tab
        _tabArr = [NSMutableArray new];
        CGFloat width = (ScreenWidth-self.cardBtn.width)/4;
        NSArray * title = @[STR(@"Mood"),STR(@"Notepad"),STR(@"Today"),STR(@"Deletes")];
        for (NSInteger i=0; i<title.count; i++) {
            UIButton * tab = [UIButton buttonWithType: UIButtonTypeCustom];
            tab.width = width;
            tab.height = 49;
            NSString * str = title[i];
            if (i<2) {
                tab.left = width*i;
            }else{
                tab.left = self.cardBtn.right+width*(i-2);
            }
            [tab setTitle: str forState: UIControlStateNormal];
            [tab setTitleColor: [UIColor blackColor] forState: UIControlStateNormal];
            tab.titleLabel.font = [UIFont systemFontOfSize: 14];
            tab.tag = i;
            [tab addTarget: self action: @selector(onTab:) forControlEvents: UIControlEventTouchUpInside];
            [_bottomView addSubview: tab];
            [_tabArr addObject: tab];
            if (i==1) {
               [tab setTitleColor: RGB(57, 199, 197) forState: UIControlStateNormal];
               _lastIndex = tab;
            }
        }
    }
    return _bottomView;
}
- (UIButton *)cardBtn
{
    if (nil == _cardBtn) {
        _cardBtn = [UIButton buttonWithType: UIButtonTypeCustom];
        [_bottomView addSubview: _cardBtn];
        UIImage * image = [UIImage imageNamed: @"CheckInIcon"];
        _cardBtn.size = CGSizeMake(image.size.width, image.size.height);
        _cardBtn.top = self.bottomView.top - _cardBtn.height/3;
        _cardBtn.left = (ScreenWidth - _cardBtn.width)/2;
        [_cardBtn addTarget: self action: @selector(add:) forControlEvents: UIControlEventTouchUpInside];
        [_cardBtn setImage: image forState: UIControlStateNormal];
        [_cardBtn setImage: image forState: UIControlStateHighlighted];
    }
    return _cardBtn;
}
- (UIView *)nodataView
{
    if (nil == _nodataView) {
        _nodataView = [[UIView alloc] initWithFrame: self.tableView.bounds];
        UIImageView * image = [[UIImageView alloc] initWithImage: [UIImage imageNamed: @"noData"]];
        [_nodataView addSubview: image];
        CGFloat top = (_nodataView.height-image.height-60)/2;
        image.top = top;
        image.left = (ScreenWidth-image.width)/2;
        UILabel * label = [[UILabel alloc] initWithFrame: CGRectMake(0, image.bottom, ScreenWidth, 60)];
        label.text = STR(@"nodatatips");
        label.textAlignment = NSTextAlignmentCenter;
        label.numberOfLines = 0;
        [_nodataView addSubview: label];
        label.font = [UIFont systemFontOfSize: 16];
        label.textColor = [UIColor blackColor];
        _nodataView.hidden = YES;
    }
    return _nodataView;
}
#pragma mark - Table View Delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView * headerView = [[UIView alloc]initWithFrame: CGRectMake(0, 0, ScreenWidth, 30)];
    headerView.backgroundColor = _tableView.backgroundColor;
    UILabel * labelTime = [[UILabel alloc]initWithFrame: CGRectMake(15.f, 0, ScreenWidth-15.f, 30)];
    [headerView addSubview: labelTime];
    NSArray * arr = self.dataSource[section];
    MoodObj * obj = [arr firstObject];
    labelTime.text = obj.creatDate;
    labelTime.font = [UIFont systemFontOfSize: 14.f];
    labelTime.textColor = RGB(136, 136, 136);
    return headerView;
}

#pragma mark-UITableViewDataSource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MoodObj * model = self.dataSource[indexPath.section][indexPath.row];
    HistoryTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier: HistoryTableViewCellID forIndexPath: indexPath];
    cell.model = model;
    return cell;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray * source = self.dataSource[section];
    return  source.count;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
       MoodObj * model = self.dataSource[indexPath.section][indexPath.row];
        [[MyDbTools sharedInstance] deleteId: model.Id Success:^(BOOL success) {
            if (success) {
                NSMutableArray * source = self.dataSource[indexPath.section];
                [source removeObject: model];
                if (source.count == 0) {
                    [self.dataSource removeObject: source];
                }
                [tableView reloadData];
            }
        }];
    }
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MoodObj * model = self.dataSource[indexPath.section][indexPath.row];
    DeatailViewController * detail = [[DeatailViewController alloc] initWithObj: model Image: self.bgImageView.image];
    [self.navigationController pushViewController: detail animated: YES];
}
@end
